package cn.fl.warrant.controller;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.fl.warrant.service.IArcRouteDetailService;
import cn.fl.warrant.service.IArcRouteMainService;
import cn.fl.warrant.vo.ArcRouteDetailVO;
import cn.fl.warrant.vo.ArcRouteMainVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.vo.SysUsrVO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.condition.SysOrgQueryCondition;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import fl.warrant.facade.archive.condition.ArcRouteDetailQueryCondition;
import fl.warrant.facade.archive.condition.ArcRouteMainQueryCondition;
import fl.warrant.facade.archive.constant.ArchiveConstants;

/**
 * @Description: 巡检主表 控制层
 */
@Controller
@RequestMapping("/archive/arcRouteMain")
public class ArcRouteMainController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcRouteMainController.class);

	/**
	 * ArcRouteMain 服务层BEAN
	 */
	@Autowired
	private IArcRouteMainService arcRouteMainService;
	
	/**
	 * 客户 服务层BEAN
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	
	@Autowired
	private IArcRouteDetailService arcRouteDetailService;//巡检明细
	
	@Autowired
	private ISysUsrService sysUsrService;//系统用户

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("archive/arcRouteMain/arcRouteMainList");
		this.setAttribute(request);
		view.addObject("currentBuOrgCd", CurrentThreadContext.getCurrentBuOrgCd());
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 获取事业部列表数据
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getBusinessOrgList.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object getBusinessOrgList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
			if(CollectionUtils.isEmpty(orgList)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在！");
				BaseLogUtils.info(logger, "getBusinessOrgList", "获取事业部列表数据,数据不存在.", CurrentThreadContext.getCurrentUserName());
			}
			JSONArray orgListJson = JSONArray.fromObject(orgList.toArray());
			result.setData(orgListJson);
			BaseLogUtils.info(logger, "getBusinessOrgList", "获取事业部列表数据.", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "getBusinessOrgList", "获取事业部列表失败1.", CurrentThreadContext.getCurrentUserName(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getBusinessOrgList", "获取事业部列表失败2.", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
	
	/**
	 * 获取省公司列表数据
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getProvOrgList.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object getProvOrgList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String orgCd = request.getParameter("orgCd");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			SysOrgQueryCondition qc = new SysOrgQueryCondition();
			qc.setOrgCd(orgCd);//组织架构代码
			qc.setSysCd("11000");//融资租赁系统
			qc.setOrgTypCd("3");//省公司
			List<KeyValueVO> orgList = this.arcRouteMainService.searchProvOrgList(qc);
			if(CollectionUtils.isEmpty(orgList)){
				//result.setSuccess(BaseConstant.IS_YESNO_NO);
				//result.setInfo("数据不存在！");
				//BaseLogUtils.info(logger, "getProvOrgList", "获取省公司列表数据,数据不存在.orgCd="+orgCd, CurrentThreadContext.getCurrentUserName());
				//return result;
			}else{
				JSONArray orgListJson = JSONArray.fromObject(orgList.toArray());
				result.setData(orgListJson);
				BaseLogUtils.info(logger, "getProvOrgList", "获取省公司列表数据.", CurrentThreadContext.getCurrentUserName());
			}
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "getProvOrgList", "获取省公司列表失败1.", CurrentThreadContext.getCurrentUserName(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getProvOrgList", "获取省公司列表失败2.", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("archive/arcRouteMain/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到巡检结果详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String btnFlag = request.getParameter("btnFlag");
		String id = request.getParameter("id");
		String upFlag = request.getParameter("upFlag");//是否更新巡检时间等值
		ModelAndView view = new ModelAndView("archive/arcRouteMain/arcRouteMainDetail");
		//判断是查看或是更新
		if("no".equals(btnFlag)){
			view.addObject("operation", "look");
		}else{
			view.addObject("operation", "update");
		}
		//查询对应的巡检信息
		if(StringUtils.isNotEmpty(id)){
			//定义巡检人员
			String inspectors = "";
			Set<String> personList = new HashSet<String>();
			
			//1.查询巡检明细信息
			ArcRouteDetailQueryCondition qc2 = new ArcRouteDetailQueryCondition();
			qc2.setArcRouteMainId(Long.parseLong(id));
			qc2.setIsValid(1);
			qc2.setIsDel(0);
			List<ArcRouteDetailVO> detailList = this.arcRouteDetailService.searchList(qc2);
			if(CollectionUtils.isNotEmpty(detailList) && null != detailList.get(0)){
				btnFlag = "no";//有巡检明细数据就不可以再次刷新了
				//设置巡检开始和结束时间
				Date minDate = ((null != detailList.get(0).getMdfTm()) ? detailList.get(0).getMdfTm() : detailList.get(0).getCrtTm());
				Date maxDate = ((null != detailList.get(0).getMdfTm()) ? detailList.get(0).getMdfTm() : detailList.get(0).getCrtTm());
				String sysCd = CurrentThreadContext.getCurrentSysCd();
				for(ArcRouteDetailVO vo : detailList){
					//获取巡检人员-真实姓名
					Long usrId = ((null != vo.getMdfUsrId()) ? vo.getMdfUsrId() : vo.getCrtUsrId());
					SysUsrVO usrVo = this.sysUsrService.selectById(usrId, sysCd);
					if(usrVo != null){
						personList.add(usrVo.getRefRlNm());
					}
					//判断是否有"巡检中"和"已巡检"的数据
					//if("1".equals(vo.getRouteState()) || "2".equals(vo.getRouteState())){
						//btnFlag = "no";
					//}
					//判断是否有"巡检中"和"未巡检"的数据
					if("1".equals(vo.getRouteState()) || "0".equals(vo.getRouteState())){
						upFlag = "no";
					}
					//判断巡检时间是否为空
					if(null != vo.getMdfTm()){
						//如果最小时间晚于此条记录时间
						if(minDate.after(vo.getMdfTm())){
							minDate = vo.getMdfTm();
						}
						//如果最小时间晚于此条记录时间
						if(maxDate.before(vo.getMdfTm())){
							maxDate = vo.getMdfTm();
						}
					}
				}
				//巡检记录下其他支付表状态均为“巡检结束”时：
				//更新巡检记录的“巡检开始时间”为所有支付表巡检结束最早时间；
				//更新巡检记录的“巡检结束时间”为所有支付表巡检结束最晚时间；
				//更新巡检记录的巡检人为：所有支付表巡检人的去重集合；
				if(StringUtils.isNotEmpty(upFlag) && "yes".equals(upFlag)){
					ArcRouteMainVO entity = new ArcRouteMainVO();
					entity.setId(Long.parseLong(id));
					entity.setRouteState("2");//巡检结束
					entity.setRouteBeginDate(minDate);
					entity.setRouteEndDate(maxDate);
					entity.setMdfTm(new Date());
					entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
					boolean success = this.arcRouteMainService.modify(entity);
					if(success){
						BaseLogUtils.info(logger, "toDetailPage", "更新巡检主表-巡检时间/状态-成功.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
					}else{
						BaseLogUtils.info(logger, "toDetailPage", "更新巡检主表-巡检时间/状态-失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
					}
				}
			}
			//获取巡检人员名单
			int n = 1;
			for(String set : personList){
				if(n > 1){
					inspectors += ',';
				}
				inspectors += set;
				n++;
			}
			//2.查询巡检主表信息
			ArcRouteMainVO routeMainVo = this.arcRouteMainService.selectById(Long.parseLong(id));
			//设置巡检主数据
			if(routeMainVo != null){
				routeMainVo.setInspectors(inspectors);
				view.addObject("routeMainVo", routeMainVo);
			}
		}
		view.addObject("id", id);
		view.addObject("btnFlag", btnFlag);
		BaseLogUtils.info(logger, "toDetailPage", "跳转到巡检结果详情页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		this.setAttribute(request);
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String routeNo = request.getParameter("routeNo");
		String bussDepartment = request.getParameter("bussDepartment");
		String proCompany = request.getParameter("proCompany");
		String routeState = request.getParameter("routeState");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		ArcRouteMainQueryCondition qc = new ArcRouteMainQueryCondition();
		if (StringUtils.isNotEmpty(routeNo)) {
			qc.setRouteNo(routeNo);
		}
		if (StringUtils.isNotEmpty(bussDepartment)) {
			qc.setBussDepartment(bussDepartment);
		}
		if (StringUtils.isNotEmpty(proCompany)) {
			qc.setProCompany(proCompany);
		}
		if (StringUtils.isNotEmpty(routeState)) {
			qc.setRouteState(routeState);
		}
		page.setCondition(qc);

		//分页条件查询列表
		Pager pager = this.arcRouteMainService.searchListPage(page);
		List<ArcRouteMainVO> list = (List<ArcRouteMainVO>) pager.getResultList();
		ListPageVO<ArcRouteMainVO> listPage = new ListPageVO<ArcRouteMainVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.arcRouteMainService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			ArcRouteMainVO vo = this.arcRouteMainService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			Long currentUserId = CurrentThreadContext.getCurrentUserId();
			//批量生成返回逻辑值
			boolean flag = this.arcRouteMainService.batchAdd(currentUserId);
			if(!flag){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("批量生成巡检记录失败！");
			}
			BaseLogUtils.info(logger, "add", "批量生成巡检记录.[flag="+flag+"]" + JSONObject.toJSONString(result), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "add", "批量生成巡检记录失败1.", CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "批量生成巡检记录失败2.", CurrentThreadContext.getCurrentUserName(), ex);
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		ArcRouteMainVO entity = null;
		try {
			entity = new ArcRouteMainVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.arcRouteMainService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	private void setAttribute(HttpServletRequest request) {
		//事业部组织架构集合
		request.setAttribute("OrgList", this.cstBscInfoService.searchBusinessOrgList());
	}
}

